package com.sunmouse.toollib.utils.region;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;


/**
 * Created by Kvin on 2017/5/26.
 */
public class XmlParserHandler extends DefaultHandler {

    private ArrayList<ProvinceBean> provinceList = new ArrayList<>();
    private ProvinceBean mProvince;
    private CityBean mCity;
    private DistrictBean mDistrict;

    public static final String QUALIFIED_PROVINCE = "province";
    public static final String QUALIFIED_CITY = "city";
    public static final String QUALIFIED_DISTRICT = "district";


    /**
     * get province data
     */
    public ArrayList<ProvinceBean> getProvinceList() {
        return provinceList;
    }


    @Override
    public void startDocument() throws SAXException {
    }

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equals(QUALIFIED_PROVINCE)) {
            mProvince = new ProvinceBean();
            mProvince.setName(attributes.getValue(0));
            mProvince.setCityList(new ArrayList<CityBean>());
//            LogUtils.d("--------"+attributes.getLocalName(0)+" "+attributes.getQName(0)+" "+attributes.getValue(0) );
        } else if (qName.equals(QUALIFIED_CITY)) {
            mCity = new CityBean();
            mCity.setName(attributes.getValue(0));
            mCity.setDistrictList(new ArrayList<DistrictBean>());
//            LogUtils.d("--------"+attributes.getLocalName(0)+" "+attributes.getQName(0)+" "+attributes.getValue(0) );
        } else if (qName.equals(QUALIFIED_DISTRICT)) {
            mDistrict = new DistrictBean();
            mDistrict.setName(attributes.getValue(0));
            mDistrict.setZipcode(attributes.getValue(1));
//            LogUtils.d("--------" + attributes.getLocalName(0) + " " + attributes.getQName(0) + " " + attributes.getValue(0));
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals(QUALIFIED_PROVINCE)) {
            provinceList.add(mProvince);
        } else if (qName.equals(QUALIFIED_CITY)) {
            mProvince.getCityList().add(mCity);
        } else if (qName.equals(QUALIFIED_DISTRICT)) {
            mCity.getDistrictList().add(mDistrict);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
    }
}
